<script setup lang="ts">
import { addOneRolePerm, getPermList, getRoleList } from '@/api/auth';
import type { Perm, Role, RolePerm, UserRole } from '@/api/auth/type';
import { onMounted, ref } from 'vue';
import YAddRole from './components/YAddRole.vue';
import { ElMessage } from 'element-plus';

const onShow = ref(false)
const dialogFormVisible = ref(false);
const roleList = ref([] as Role[]);
const permList = ref([] as Perm[]);
const rolePerm = ref({} as RolePerm);

onMounted(() => {
    getRoleList().then((res) => {
        roleList.value = res.data as Role[];
    })
    getPermList().then((res) => {
        permList.value = res.data as Perm[];
    })
})

const addRolePerm = () => {
    addOneRolePerm(rolePerm.value).then((res) => {
        if (res.code === 5200) {
            ElMessage.success(res.msg);
        } else {
            ElMessage.error("错误码:"+res.code+"\n错误信息: "+res.msg);
        }
    });
    dialogFormVisible.value = false;
}
</script>

<template>
    
    <div class="content">
        <div class="header">
            <el-button @click="onShow = true" type="primary">添加</el-button>
            <el-button @click="dialogFormVisible = true" type="primary">
                角色添加权限
            </el-button>
            <el-dialog v-model="dialogFormVisible" title="角色添加权限" width="500">
                <el-form :model="rolePerm" label-width="auto" style="max-width: 300px">
                    <el-form-item label="权限名">
                        <el-select v-model="rolePerm.permName" placeholder="请选择权限">
                            <el-option v-for="perm in permList" :label="perm.name" :value="perm.name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="角色名">
                        <el-select v-model="rolePerm.roleName" placeholder="请选择角色">
                            <el-option v-for="role in roleList" :lable="role.name" :value="role.name"/>
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="addRolePerm">确认</el-button>
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <el-table :data="roleList" style="width: 100%" stripe border>
            <el-table-column prop="name" label="角色名" />
            <el-table-column prop="code" label="角色编码" />
        </el-table>
    </div>
    <YAddRole v-model:on-show="onShow"></YAddRole>
</template>

<style lang="scss" scoped>
.content {
    background-color: white;
    padding: 1%;
    .header {
        padding: 1%;
    }
}
</style>